import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'

// 创建axios实例
const request = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000/api',
    timeout: 30000, // 30秒超时
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
request.interceptors.request.use(
    config => {
        // 从store获取token
        const token = store.state.token
        console.log('Request config:', {
            url: config.url,
            method: config.method,
            params: config.params,
            data: config.data
        })
        
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
            console.log('Using token:', token)
        } else {
            console.warn('No token found in store')
        }
        return config
    },
    error => {
        console.error('Request interceptor error:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        console.log('Response received:', {
            status: response.status,
            data: response.data,
            headers: response.headers
        })
        return response.data
    },
    error => {
        console.error('Response interceptor error:', error)
        
        if (error.response) {
            console.error('Error response:', {
                status: error.response.status,
                data: error.response.data,
                headers: error.response.headers
            })
            
            switch (error.response.status) {
                case 401:
                    store.dispatch('logout')
                    window.location.href = '/login'
                    ElMessage.error('登录已过期，请重新登录')
                    break
                case 403:
                    ElMessage.error('没有权限访问该资源')
                    break
                case 404:
                    ElMessage.error('请求的资源不存在')
                    break
                case 500:
                    ElMessage.error('服务器错误：' + (error.response.data?.message || '未知错误'))
                    break
                default:
                    ElMessage.error(error.response.data?.message || '请求失败')
            }
        } else if (error.request) {
            console.error('No response received:', error.request)
            ElMessage.error('服务器未响应，请检查网络连接')
        } else {
            console.error('Error details:', error)
            ElMessage.error('请求发生错误：' + error.message)
        }

        return Promise.reject(error)
    }
)

export default request 